package com.example.db.dept

import org.apache.ibatis.io.Resources
import org.apache.ibatis.session.SqlSession
import org.apache.ibatis.session.SqlSessionFactory
import org.apache.ibatis.session.SqlSessionFactoryBuilder
import java.io.IOException
import java.io.InputStream
import java.sql.DriverManager
import kotlin.concurrent.thread


/**
 * @Author: h2和mybats的结合使用，实现了数据的插入和查询
 */
object DeptTest {
    private var sqlSession: SqlSession? = null
    val jdbcUrl = "jdbc:h2:file:C:/data/sample1"
    val userName = "sa"
    val pwd = ""
    fun initSEssion() {
        if (sqlSession != null) return
        val ssfb = SqlSessionFactoryBuilder()
        var resourceAsStream: InputStream? = null
        try {
            resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml")
        } catch (e: IOException) {
            e.printStackTrace()
        }
        val factory: SqlSessionFactory = ssfb.build(resourceAsStream)
        sqlSession = factory.openSession()
        createDb()
    }
    fun createDb() {
        val deptSql = "CREATE TABLE IF NOT EXISTS dept (deptno INTEGER, dname TEXT, loc TEXT)"
        DriverManager.getConnection(jdbcUrl, userName,pwd).prepareStatement(deptSql).execute()

    }
    fun insert(dept: Dept){
        initSEssion()
        sqlSession?.getMapper(DeptMapper::class.java)?.let {
            it.insert(dept)
        }
    }
    fun queryDept(){
        initSEssion()
        sqlSession?.getMapper(DeptMapper::class.java)?.let {
            it.findAll().forEach {
                println(it)
            }
        }
    }
}


fun main() {
    DeptTest.insert(Dept(2,"杜甫","南京"))
    DeptTest.queryDept()

}